//
//  YKURLCache.m
//  YKKit
//
//  Created by 马洪伟 on 16/1/19.
//  Copyright © 2016年 悦康动力（北京）科技有限公司. All rights reserved.
//

#import "YKURLCache.h"

static NSMutableDictionary *substitutions;
static NSMutableDictionary *cachedResponses;

@implementation YKURLCache
+ (void)initialize {
    if (self == [YKURLCache class]) {
        substitutions = [NSMutableDictionary dictionary];
        cachedResponses = [NSMutableDictionary dictionary];
    }
}

+ (void)addSubstitution:(YKURLResponseSubstitution *)substitution {
    [substitutions setObject:substitution forKey:substitution.url];
}

+ (void)removeSubstitutionForUrl:(NSString *)url {
    NSString *requestUrl = url;
    if ([requestUrl hasSuffix:@"/"]) {
        requestUrl = [requestUrl substringToIndex:requestUrl.length-1];
    }
    [substitutions removeObjectForKey:requestUrl];
    [cachedResponses removeObjectForKey:requestUrl];
}

- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request {
    NSString *requestUrl = [self urlForRequest:request];
    
    // 判断是否为这个请求加载本地（缓存）替换资源
    YKURLResponseSubstitution *substitution = [substitutions objectForKey:requestUrl];
    if (!substitution) {
        return [super cachedResponseForRequest:request];
    }
    
    NSCachedURLResponse *cachedResponse = [cachedResponses objectForKey:requestUrl];
    if (cachedResponse) {
        return cachedResponse;
    }
    
    NSData *data = nil;
    if (substitution.filePath) {
        @try {
            data = [NSData dataWithContentsOfFile:substitution.filePath];
        }
        @catch (NSException *exception) {
            data = nil;
        }
        @finally {}
    }
    if (!data) {
        data = substitution.data;
    }
    if (!data) {
        return [super cachedResponseForRequest:request];
    }
    
    NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL MIMEType:substitution.mimeType expectedContentLength:[data length] textEncodingName:@"utf-8"];
    cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data];
    
    // 加入缓存中
    [cachedResponses setObject:cachedResponse forKey:requestUrl];

    return cachedResponse;
}

- (NSString *)urlForRequest:(NSURLRequest *)request {
    NSString *requestUrl = [request.URL absoluteString];
    if ([requestUrl hasSuffix:@"/"]) {
        requestUrl = [requestUrl substringToIndex:requestUrl.length-1];
    }
    return requestUrl;
}
@end
